from pylab import *
import matplotlib.pyplot as plt
from multiplylib import *
from matplotlib import colors

plt.interactive(True)

# complex code which produces multiple figures goes here...

# # ... and might do something like 
# fig1 = plt.figure()
# plt.plot(range(10))
# plt.draw()

# # ... or this
# fig2 = plt.figure()
# plt.polar(range(10))
# plt.draw()

# # once everything is done, we can put in a blocking call
# # which will terminate when the last window is closed by the user
# # plt.show(block=dsfsdTrue)
# plt.show(block=False)

import time
# time.sleep(5)
from random import random
# figure()
new_fig()
plt.show(block=False)
        
# while True:
#     s = raw_input()
#     print "you input : ", s
#     if s == "new":
#         x = array(range(100))
#         m = array(random()*3)
#         plt.plot(x,x**m)
#         plt.show(block=False)

# for i in range(10):
#     x = array(range(100))
#     m = array(random()*3)
#     plt.plot(x,x**m)
#     plt.show(block=False)
#     print "OK"
#     time.sleep(2)
    
# plt.show()

x = linspace(0,10,100)


def get_color(index):
    cmap = cm.jet
    norm = colors.Normalize(vmin=0,vmax=9)
    return cmap(norm(index))

bar_width = 10

def update_histogram_bar(index):
    global val_list
    plot_rect((0,index*bar_width), (val_list[index],(index+1)*bar_width-1), color=get_color(index))

def histogram_init():
    global val_list
    val_list = [0 for i in range(10)]
    cla()
    for i in range(10):
        # update_histogram_bar(i)
        plot_rect((0,i*bar_width), (200,(i+1)*bar_width-1), color=get_color(i), fill=False)
        

        
def histogram_increase(index):
    global val_list
    val_list[index] += 5
    update_histogram_bar(index)

    
def plot_some(cmd):
    if cmd == "clear":
        histogram_init()
        return
    
    try:
        index = int(cmd)
        if index>=0 and index<=9:
            histogram_increase(int(cmd))
        else:
            print "'%s' not valid" % cmd
    except:
        print "'%s' not valid" % cmd

    # if cmd == "sin":
    #     plot_rect((0,10), (100,20), color="red")
    # elif cmd == "cos":
    #     plot_rect((0,10), (100,20), color="blue")


import socket
sockin = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockin.bind(("127.0.0.1", 8080))

histogram_init()
plt.draw()
plt.show(block=False)

print "waiting for msg"
while True:
    msg, (addr,port) = sockin.recvfrom(100)
    print "receive : ", msg
    # if msg == "test":
    #     m = array(random()*3)
    #     plt.plot(x,x**m)
    #     plot_some()
    #     plt.draw()
    #     plt.show(block=False)

    plot_some(msg)
    plt.draw()
    plt.show(block=False)

        
